<template>
  <div>
    <div>
      <!-- 答案信息表单 -->
      <FormPanel ref="formPanel" :list="formList" formType="add" labelWidth="100" :isSubmitBtn="false" @formChange="formChangeHandle" />
      <!-- 问题组表格 -->
      <FilterTable
        ref="table"
        :columns="questionColumns"
        :isPagination="false"
        :dataSource="questionList"
        :isSelectColumn="false"
        :isToperInfo="false"
        :isColumnFilter="false"
        :height="'auto'"
        columnsRef="wjdyMbxzWtzTable"
        :onSyncTableData="syncTableFun"
        :onColumnsChange="columns => (this.questionColumns = columns)"
      >
        <template slot="controls">
          <el-tag style="margin-right:10px">问题组</el-tag>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addQuestion">新建问题</el-button>
        </template>
      </FilterTable>
    </div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <div
        :style="{
          position: 'absolute',
          left: '20px',
          color: 'red',
          width: '200px'
        }"
      >
        *答案选项以英文逗号分隔
      </div>
      <el-button @click="closeDrawer(false)">取 消</el-button>
      <el-button type="primary" :loading="loginBtnState" @click="commit">提 交</el-button>
    </div>

    <!-- 弹框 -->
    <BaseDialog title="答案选择" :modal="false" :visible.sync="dialogVisible" width="80%">
      <answerGroupSelect @fatherReq="req" @fatherGoBack="goBack" />
    </BaseDialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import moment from 'moment';
import * as types from '@/api/customerRepair/visitRules/questionnaireMake2/types';
import { getAnswerEditInfo, delAnswerById, saveAnswerInfo, delQuestionById, saveQuestionnaire, getQuestionnaireEditInfo } from '@/api/customerRepair/visitRules/questionnaireMake2';
import { dictionary } from '@/utils/dictMixin';
import answerGroupSelect from '../components/answerGroupSelect';

export default {
  name: 'TemplateQuestionnairePanel',
  components: {
    answerGroupSelect
  },
  mixins: [dictionary],
  props: {
    questionnaireId: String,
    type: String
  },
  data() {
    this.BaseTable = null;
    return {
      formList: this.createFormList(), // 问卷表单
      questionList: [], // 问题表格List
      questionColumns: this.createQuestionColumns(), // 问题表格列
      isSaveTemplate: false, // 是否保存为模板
      dialogVisible: false, // 是否显示dia
      chooseAnswerIndex: -1 // 当前正在进行选择答案的行
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    loginBtnState() {
      return this.btnLoading[types.SAVE];
    }
  },
  created() {
    this.getQuestionnaire();
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    // 获取模板信息
    async getQuestionnaire() {
      if (this.questionnaireId && this.questionnaireId.length > 0) {
        const res = await getQuestionnaireEditInfo(this.questionnaireId);
        if (res.resultCode == 200) {
          this.questionnaire = res.data;
          this.questionList = res.data.questionList;
        } else {
          this.$message.error('获取模板信息失败');
          return;
        }
      } else {
        this.questionnaire = {
          questionnaireName: '',
          questionnaireType: '',
          isValid: 10041001, // 是
          dataSources: 10451001, // 店端
          isTemplate: 10041001 // 模板
        };
        this.questionList = [];
      }
      this.formList[0].initialValue = this.questionnaire.questionnaireName;
      this.formList[1].initialValue = this.questionnaire.questionnaireType;
      this.formList[2].initialValue = this.questionnaire.isValid;
      this.formList[3].initialValue = this.questionnaire.dataSources;
      this.formList = [...this.formList];
      this.questionList = [...this.questionList];
    },
    // 问卷表单列
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '模板名称',
          fieldName: 'questionnaireName',
          disabled: this.type == 'edit',
          rules: [{ required: true, message: '请填写模板名称', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '模板类型',
          fieldName: 'questionnaireType',
          itemList: this.createDictList('8003'),
          rules: [{ required: true, message: '请选择模板类型', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '是否启用',
          fieldName: 'isValid',
          itemList: this.createDictList('1004'),
          rules: [{ required: true, message: '请选择是否启用', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'dataSources',
          itemList: this.createDictList('1045'),
          disabled: true
        }
      ];
    },
    // 问题表格列
    createQuestionColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={props.row.questionId ? true : false} onClick={() => this.delQuestion(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '问题名称',
          dataIndex: 'questionName',
          showOverflowTooltip: true,
          editable: true,
          editType: 'input',
          editRequired: true,
          rules: [{ required: true, message: '请填写问题名称', trigger: 'blur' }],
          defaultEditable: true
        },
        {
          title: '问题内容',
          dataIndex: 'questionContent',
          editable: true,
          editType: 'input',
          editRequired: true,
          rules: [{ required: true, message: '请填写问题内容', trigger: 'blur' }],
          defaultEditable: true
        },
        {
          title: '问题类型',
          dataIndex: 'questionType',
          editable: true,
          editType: 'select',
          editRequired: true,
          editItems: this.createDictList('8074'),
          defaultEditable: true
        },
        {
          title: '答案名称',
          dataIndex: 'answerGroupName',
          width: 180,
          editable: true,
          editType: 'input',
          editRequired: true,
          render: props => {
            return (
              <el-input placeholder="答案名称" v-model={props.row.answerGroupName} disabled={props.row.questionId ? true : false}>
                <i slot="suffix" class="el-input__icon el-icon-circle-plus" onClick={() => this.openDia(props.row)}></i>
                <i slot="suffix" class="el-input__icon el-icon-error" onClick={() => this.delAnswer(props.row)}></i>
              </el-input>
            );
          }
        },
        {
          title: '答案选项',
          dataIndex: 'answer',
          width: 200,
          render: props => {
            return <el-input placeholder="选项以英文逗号分隔" v-model={props.row.answer} disabled={props.row.questionId ? true : false}></el-input>;
          }
        },
        {
          title: '是否必填',
          dataIndex: 'isMustFilled',
          editable: true,
          editType: 'select',
          editItems: this.createDictList('1004'),
          defaultEditable: true
        },
        {
          title: '排列顺序',
          dataIndex: 'questionSortNum',
          width: 80,
          editable: true,
          editType: 'input',
          editRequired: true,
          editPattern: /^[0-9]+$/,
          defaultEditable: true
        }
      ];
    },
    // 监听表格数据
    syncTableFun(val) {
      // 通过监听表格数据，给服务活动带过来的数据添加表格编辑禁用
      if (val && val.length > 0) {
        for (const obj of val) {
          // 如果有id不让编辑
          if (obj.questionId) {
            this.BaseTable.SET_CELL_DISABLED(obj, 'questionName', true);
            this.BaseTable.SET_CELL_DISABLED(obj, 'questionContent', true);
            this.BaseTable.SET_CELL_DISABLED(obj, 'questionType', true);
            this.BaseTable.SET_CELL_DISABLED(obj, 'answer', true);
          }
        }
      }
    },
    // 关闭drawer
    closeDrawer(refresh) {
      if (refresh) {
        this.$emit('changeHandle', { dataSources: 10451001 });
      }
      this.$emit('close', false);
    },
    // 新增问题
    addQuestion() {
      let question = {
        questionName: '',
        questionContent: '',
        questionType: '',
        answerGroupId: '',
        answerGroupName: '',
        answer: '',
        isMustFilled: 10041001,
        questionSortNum: this.questionList.length + 1
      };
      this.questionList.push(question);
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    // 删除问题
    delQuestion(row) {
      if (this.questionList.length === 1) {
        this.$message.info('请保留至少一个问题');
        return;
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 有questionId，直接真删，再从questionList中移除
          if (row.questionId) {
            delQuestionById(row.questionId)
              .then(res => {
                this.questionList.splice(row.$index, 1);
              })
              .catch(err => {
                this.$message.error('删除失败');
              });
          } else {
            // 没有questionId，直接从questionList中移除
            this.questionList.splice(row.$index, 1);
          }
        })
        .catch(() => {});
    },
    // 点击提交
    commit() {
      // 调用表单验证
      this.$refs.formPanel.SUBMIT_FORM();
    },
    // 表单验证回调，传回表单参数
    formChangeHandle(val) {
      if (this.questionList.length === 0) {
        this.$message.info('请添加问题信息');
        return;
      }
      let a = true;
      let questionSortNumArr = [];
      for (let i = 0; i < this.questionList.length; i++) {
        if (this.questionList[i].questionName == '' || this.questionList[i].questionName == null || this.questionList[i].questionName == undefined) {
          this.$message({
            type: 'info',
            message: '第' + (i + 1) + '行问题名称不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].questionContent == '' || this.questionList[i].questionContent == null || this.questionList[i].questionContent == undefined) {
          this.$message({
            type: 'info',
            message: '第' + (i + 1) + '行问题内容不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].questionType == '' || this.questionList[i].questionType == null || this.questionList[i].questionType == undefined) {
          this.$message({
            type: 'info',
            message: '第' + (i + 1) + '行问题类型不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].answerGroupName == '' || this.questionList[i].answerGroupName == null || this.questionList[i].answerGroupName == undefined) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行请填写答案名称!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].isMustFilled == '' || this.questionList[i].isMustFilled == null || this.questionList[i].isMustFilled == undefined) {
          this.$message({
            type: 'info',
            message: '第' + (i + 1) + '行是否必填不能为空!'
          });
          a = false;
          break;
        }
        if (this.questionList[i].questionSortNum == '' || this.questionList[i].questionSortNum == null || this.questionList[i].questionSortNum == undefined) {
          this.$message({
            type: 'info',
            message: '第' + (i + 1) + '行排列顺序不能为空!'
          });
          a = false;
          break;
        }
        if (questionSortNumArr.indexOf(parseInt(this.questionList[i].questionSortNum)) != -1) {
          this.$message({
            type: 'error',
            message: '第' + (i + 1) + '行排列顺序不能重复!'
          });
          a = false;
          break;
        }
        questionSortNumArr.push(parseInt(this.questionList[i].questionSortNum));
      }
      if (a) {
        this.questionnaire.questionnaireName = val.questionnaireName;
        this.questionnaire.questionnaireType = val.questionnaireType;
        this.questionnaire.isValid = val.isValid;
        this.questionnaire.dataSources = val.dataSources;
        this.questionnaire.questionList = this.questionList;
        saveQuestionnaire(this.questionnaire).then(res => {
          if (res.resultCode === 200) {
            this.$message.success('保存成功');
            this.closeDrawer(true);
          } else {
            this.$message.error('保存失败');
          }
        });
      }
    },
    // 打开选择答案dia
    openDia(row) {
      if (!row.questionId) {
        this.dialogVisible = true;
        this.chooseAnswerIndex = row.$index;
      }
    },
    // 清除选择的答案
    delAnswer(row) {
      if (!row.questionId) {
        this.chooseAnswerIndex = row.$index;
        if (this.chooseAnswerIndex !== -1) {
          this.$set(this.questionList[this.chooseAnswerIndex], 'answerGroupId', '');
          this.$set(this.questionList[this.chooseAnswerIndex], 'answerGroupName', '');
          this.$set(this.questionList[this.chooseAnswerIndex], 'answer', '');
        }
      }
    },
    goBack() {
      this.dialogVisible = false;
    },
    // 确定选择答案
    req(val) {
      if (this.chooseAnswerIndex !== -1) {
        this.$set(this.questionList[this.chooseAnswerIndex], 'answerGroupId', val.answerGroupId);
        this.$set(this.questionList[this.chooseAnswerIndex], 'answerGroupName', val.answerGroupName);
        this.$set(this.questionList[this.chooseAnswerIndex], 'answer', val.answer);
        this.dialogVisible = false;
      }
    }
  }
};
</script>
<style scoped>
.cover-container {
  width: 1100px !important;
}
</style>
